package web;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieServlet extends BaseServlet{

    protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //服务器创建一个cookie
        Cookie cookie1 = new Cookie("key1","value1");
        Cookie cookie2 = new Cookie("key2","value2");
        //通过响应头给客户端一个cookie
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        response.getWriter().write("Cookie创建成功！");
    }
    protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();

        for (Cookie cookie : cookies) {
            response.getWriter().write(cookie.getName()+cookie.getValue()+"<br/>");
        }
    }
    protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Cookie cookie1 = new Cookie("key1","newValue1");

        response.addCookie(cookie1);

        response.getWriter().write("Cookie修改成功！");
    }
    protected void defaultCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie key1 = CookieUtils.findCookie("key1", request.getCookies());
        if (key1!=null){
            key1.setMaxAge(0);
            response.addCookie(key1);
            response.getWriter().write("已删除！");
        }

    }
}
